﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

/// <summary>
/// 文件公共处理类
/// </summary>
public static class FileHelper
{
    /// <summary>
    /// 将文件转换成byte[]数组
    /// </summary>
    /// <param name="fileUrl">文件路径文件名称</param>
    /// <returns>byte[]数组</returns>
    public static byte[] FileToByte(string fileUrl)
    {
        try
        {
            using (FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read))
            {
                byte[] byteArray = new byte[fs.Length];
                fs.Read(byteArray, 0, byteArray.Length);
                return byteArray;
            }
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 将byte[]数组保存成文件
    /// </summary>
    /// <param name="byteArray">byte[]数组</param>
    /// <param name="fileName">保存至硬盘的文件路径</param>
    /// <returns></returns>
    public static bool ByteToFile(byte[] byteArray,string filePath, string fileName)
    {
        bool result = false;
        try
        {

            DirectoryInfo di = new DirectoryInfo(System.Web.Hosting.HostingEnvironment.MapPath("~") + filePath);
            if (!di.Exists) { di.Create(); }


            FileStream pFileStream = null;
            try
            {
                pFileStream = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath("~") + filePath+fileName, FileMode.OpenOrCreate);
                pFileStream.Write(byteArray, 0, byteArray.Length);
                result = true;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (pFileStream != null)
                    pFileStream.Close();
            } 

            //using (FileStream fs = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath("~") + filePath, FileMode.OpenOrCreate, FileAccess.Write))
            //{
            //    fs.Write(byteArray, 0, byteArray.Length);
            //    result = true;
            //}
        }
        catch(Exception e)
        {
            throw e;
        }
        return result;
    }

  
}